package com.sc.nft.helper;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sc.nft.entity.dto.*;
import com.sc.nft.enums.ImMethodEnum;
import com.tencentyun.TLSSigAPIv2;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
@Slf4j
public class ImAccountHelper {

    public final static String key = "c7c7318a61e439dde5aba1da7cf69a219e58679d6d6d2a413bd7e9dbbbbff815";

    public final static Integer appId = 1400789568;

    public static void main(String[] args) {
        List<String>list=new ArrayList<>();

        List<Map<String, String>> maps = userHandle();
        List<List<Map<String, String>>> split = ListUtil.split(maps, 1000);
        // 每1000个人,换一个群.
//        list.add("@TGS#2JWGA3MPY");
//        list.add("@TGS#2GYNA3MP6");
//        list.add("@TGS#2L5TA3MPF");


        // 批量注册导入账号
//        List<List<Map<String, String>>> split1 = ListUtil.split(userHandle(), 100);
//        for (List<Map<String, String>> mapList : split1) {
//            new ImAccountHelper().accountImport(mapList, JSONObject.class);
//        }


        // 添入群
            List<Map<String, String>> maps1 = split.get(2);
            // maps1 把里面的id组成一个list
            List<String> collect = maps1.stream().map(s -> s.get("UserID")).collect(Collectors.toCollection(ArrayList::new));

            List<List<String>> split1 = ListUtil.split(collect, 100);
            for (List<String> strings : split1) {
                ImAddGroupMemberDTO imAddGroupMemberDTO=new ImAddGroupMemberDTO();
                imAddGroupMemberDTO.setMemberAccount(strings);
                imAddGroupMemberDTO.setGroupId(list.get(2));
                imAddGroupMemberDTO.setSilence(0);
                new ImAccountHelper().addGroupMember(imAddGroupMemberDTO,JSONObject.class);
            }


    }



    public static    List<Map<String, String>> userHandle(){
        String filePath = "C:\\Users\\PC\\Desktop\\guoxiangyuan.txt"; // 替换为实际的文件路径

        List<Map<String, String>> userDataList = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            br.readLine();
            String line;
            while ((line = br.readLine())!= null) {
                String[] fields = line.split("\t");
                if (fields.length == 3) {
                    Map<String, String> userDataMap = new HashMap<>();
                    String id = fields[0].replaceAll("\"", "");;
                    String nickName = fields[1].replaceAll("\"", "");;
                    String avatarImg = fields[2].replaceAll("\"", "");;

                    userDataMap.put("UserID", id);
                    userDataMap.put("Nick", nickName);
                    userDataMap.put("FaceUrl", avatarImg);

                    userDataList.add(userDataMap);
                } else {
                    System.out.println("无效的行格式: " + line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return userDataList;
    }






    /**
     * 导入单个账号
     *
     * @param userId
     * @param nike
     * @param faceUrl
     * @return
     */
    public Object accountImport(String userId, String nike, String faceUrl, Class tclass) {
        Map param = new HashMap();
        param.put("UserID", userId);
        param.put("Nick", nike);
        param.put("FaceUrl", faceUrl);
        return invoke(null, param, ImMethodEnum.ACCOUNT_IMPORT, tclass);
    }

    /**
     * 批量导入账号
     * @param list
     * @param tclass
     * @return
     */
    public Object accountImport(List<Map<String ,String>>list, Class tclass) {
        Map param = new HashMap();
        param.put("AccountList", list);
        return invoke(null, param, ImMethodEnum.BATCH_IMPORT_ACCOUNT, tclass);
    }

    /**
     * 修改群信息
     *
     * @param imModifyGroupBaseInfoDTO
     * @param tclass
     * @return
     */
    public Object modifyGroupBaseInfo(ImModifyGroupBaseInfoDTO imModifyGroupBaseInfoDTO, Class tclass) {
        Map param = new HashMap();
        param.put("GroupId", imModifyGroupBaseInfoDTO.getGroupId());
        param.put("Name", imModifyGroupBaseInfoDTO.getName());
//        param.put("Introduction", imModifyGroupBaseInfoDTO.getIntroduction());
//        param.put("Notification", imModifyGroupBaseInfoDTO.getNotification());
        param.put("FaceUrl", imModifyGroupBaseInfoDTO.getFaceUrl());
//        param.put("MaxMemberNum", imModifyGroupBaseInfoDTO.getMaxMemberNum());
//        param.put("ApplyJoinOption", imModifyGroupBaseInfoDTO.getApplyJoinOption());
        param.put("AppDefinedData", CollUtil.isEmpty(imModifyGroupBaseInfoDTO.getMap()) ? null : imModifyGroupBaseInfoDTO.getMap());
        param.put("MuteAllMember", imModifyGroupBaseInfoDTO.getMuteAllMember());
        return invoke(null, param, ImMethodEnum.MODIFY_GROUP_BASE_INFO, tclass);
    }

    /**
     * 删除帐号
     *
     * @param info
     * @param tclass
     * @return
     */
    public Object accountDelete(List<String> info, Class tclass) {
        Map param = new HashMap();
        List<Map> maps = new ArrayList<>();
        info.forEach(s -> {
            Map map = new HashMap();
            map.put("UserID", s);
            maps.add(map);
        });
        param.put("DeleteItem", maps);
        return invoke(null, param, ImMethodEnum.ACCOUNT_DELETE, tclass);
    }

    /**
     * 用户加入组
     *
     * @param imAddGroupMemberDTO
     * @return
     */
    public Object addGroupMember(ImAddGroupMemberDTO imAddGroupMemberDTO, Class tclass) {
        Map param = new HashMap();
        param.put("GroupId", imAddGroupMemberDTO.getGroupId());
        param.put("Silence", imAddGroupMemberDTO.getSilence());
        param.put("MemberList", imAddGroupMemberDTO.getMemberAccount());
        return invoke(null, param, ImMethodEnum.ADD_GROUP_MEMBER, tclass);
    }


    /**
     * 修改群成员资料
     *
     * @param imAddGroupMemberDTO
     * @return
     */
    public Object modifyGroupMemberInfo(ImModifyGroupMemberInfoDTO imAddGroupMemberDTO, Class tclass) {
        Map param = new HashMap();
        param.put("GroupId", imAddGroupMemberDTO.getGroupId());
        param.put("Member_Account", imAddGroupMemberDTO.getMemberAccount());
        param.put("Role", imAddGroupMemberDTO.getRole());
        param.put("MsgFlag", imAddGroupMemberDTO.getMsgFlag());
        param.put("NameCard", imAddGroupMemberDTO.getNameCard());
        param.put("AppMemberDefinedData", imAddGroupMemberDTO.getAppMemberDefinedData());
        param.put("MuteTime", imAddGroupMemberDTO.getMuteTime());
        return invoke(null, param, ImMethodEnum.MODIFY_GROUP_MEMBER_INFO, tclass);
    }

    /**
     * 解散群
     *
     * @param groupId
     * @return
     */
    public Object destroyGroup(String groupId, Class tclass) {
        Map param = new HashMap();
        param.put("GroupId", groupId);
        return invoke(null, param, ImMethodEnum.DESTROY_GROUP, tclass);
    }

    /**
     * 获取用户所加入的群组
     *
     * @param imGetJoinedGroupListDTO
     * @return
     */
    public Object getJoinedGroupList(ImGetJoinedGroupListDTO imGetJoinedGroupListDTO, Class tclass) {
        Map param = new HashMap();
        param.put("Member_Account", imGetJoinedGroupListDTO.getMemberAccount());
        param.put("WithHugeGroups", imGetJoinedGroupListDTO.getWithHugeGroups());
        param.put("WithNoActiveGroups", imGetJoinedGroupListDTO.getWithNoActiveGroups());
        if (imGetJoinedGroupListDTO.getLimit() != null) {
            param.put("Limit", imGetJoinedGroupListDTO.getLimit());
        }
        if (imGetJoinedGroupListDTO.getOffset() != null) {
            param.put("Offset", imGetJoinedGroupListDTO.getOffset() - 1);
        }
        param.put("GroupType", imGetJoinedGroupListDTO.getGroupType());
        param.put("ResponseFilter", imGetJoinedGroupListDTO.getResponseFilter());
        param.put("SupportTopic", imGetJoinedGroupListDTO.getSupportTopic());
        return invoke(null, param, ImMethodEnum.GET_JOINED_GROUP_LIST, tclass);
    }

    /**
     * 获取群详细资料
     *
     * @param imGetGroupInfoDTO
     * @param tclass
     * @return
     */
    public Object getGroupInfo(ImGetGroupInfoDTO imGetGroupInfoDTO, Class tclass) {
        Map param = new HashMap();
        param.put("GroupIdList", imGetGroupInfoDTO.getGroupIdList());
        Map map=new HashMap();
//        map.put("MemberInfoFilter",Arrays.asList("Account"));
        map.put("GroupBaseInfoFilter",Arrays.asList(
                "GroupId",
                "ErrorCode",
                "ErrorInfo",
                "Type",
                "Name",
                "FaceUrl",
                "Introduction",
                "Notification",
                "Owner_Account",
                "CreateTime",
                "LastInfoTime",
                "LastMsgTime",
                "NextMsgSeq",
                "MemberNum",
                "MaxMemberNum",
                "ApplyJoinOption",
                "MuteAllMember"
        ));
        map.put("AppDefinedDataFilter_Group",Arrays.asList(
               "lockdown"
        ));
        param.put("ResponseFilter", map);
        return invoke(null, param, ImMethodEnum.GET_GROUP_INFO, tclass);
    }



    /**
     * 查询用户在群组中的身份
     *
     * @param imGetRoleInGroupDTO
     * @param tclass
     * @return
     */
    public Object getRoleInGroup(ImGetRoleInGroupDTO imGetRoleInGroupDTO, Class tclass) {
        Map param = new HashMap();
        param.put("GroupId", imGetRoleInGroupDTO.getGroupId());
        param.put("User_Account", imGetRoleInGroupDTO.getUserAccount());
        return invoke(null, param, ImMethodEnum.GET_ROLE_IN_GROUP, tclass);
    }

    /**
     * 在群组中发送系统通知
     *
     * @param imSendGroupSystemNotificationDTO
     * @return
     */
    public Object sendGroupSystemNotification(ImSendGroupSystemNotificationDTO imSendGroupSystemNotificationDTO, Class tclass) {
        Map param = new HashMap();
        param.put("GroupId", imSendGroupSystemNotificationDTO.getGroupId());
        param.put("ToMembers_Account", imSendGroupSystemNotificationDTO.getToMembersAccount());
        param.put("Content", imSendGroupSystemNotificationDTO.getContent());
        param.put("TopicId", imSendGroupSystemNotificationDTO.getTopicId());
        return invoke(null, param, ImMethodEnum.SEND_GROUP_SYSTEM_NOTIFICATION, tclass);
    }

    public Object sendGroupMsg(ImSendGroupMsgDTO imSendGroupMsgDTO, Class tclass) {
        Map param = new HashMap();
        param.put("GroupId", imSendGroupMsgDTO.getGroupId());
        param.put("From_Account", imSendGroupMsgDTO.getFromAccount());
        param.put("Random", RandomUtil.randomNumbers(32));
        param.put("MsgBody", imSendGroupMsgDTO.getMap());
        return invoke(null, param, ImMethodEnum.SEND_GROUP_MSG, tclass);
    }

    /**
     * 删除群成员
     *
     * @param imDeleteGroupMemberDTO
     * @return
     */
    public Object deleteGroupMember(ImDeleteGroupMemberDTO imDeleteGroupMemberDTO, Class tclass) {
        Map param = new HashMap();
        param.put("GroupId", imDeleteGroupMemberDTO.getGroupId());
        param.put("Silence", imDeleteGroupMemberDTO.getSilence());
        param.put("Reason", imDeleteGroupMemberDTO.getReason());
        param.put("MemberToDel_Account", imDeleteGroupMemberDTO.getMemberDelList());
        return invoke(null, param, ImMethodEnum.DELETE_GROUP_MEMBER, tclass);
    }

    /**
     * 批量禁言和取消禁言
     *
     * @param imForbidSendMsgDTO
     * @return
     */
    public Object forbidSendMsg(ImForbidSendMsgDTO imForbidSendMsgDTO, Class tclass) {
        Map param = new HashMap();
        param.put("GroupId", imForbidSendMsgDTO.getGroupId());
        param.put("Members_Account", imForbidSendMsgDTO.getMembersAccount());
        param.put("MuteTime", imForbidSendMsgDTO.getMuteTime());
        param.put("TopicId", imForbidSendMsgDTO.getTopicId());
        return invoke(null, param, ImMethodEnum.FORBID_SEND_MSG, tclass);
    }

    /**
     * 转让群主
     *
     * @param imChangeGroupOwnerDTO
     * @return
     */
    public Object changeGroupOwner(ImChangeGroupOwnerDTO imChangeGroupOwnerDTO, Class tclass) {
        Map param = new HashMap();
        param.put("GroupId", imChangeGroupOwnerDTO.getGroupId());
        param.put("NewOwner_Account", imChangeGroupOwnerDTO.getNewOwnerAccount());
        return invoke(null, param, ImMethodEnum.CHANGE_GROUP_OWNER, tclass);
    }

    /**
     * 获取被禁言群成员列表
     *
     * @param imGetGroupMutedAccountDTO
     * @return
     */
    public Object getGroupMutedAccount(ImGetGroupMutedAccountDTO imGetGroupMutedAccountDTO, Class tclass) {
        Map param = new HashMap();
        param.put("GroupId", imGetGroupMutedAccountDTO.getGroupId());
        param.put("TopicId", imGetGroupMutedAccountDTO.getTopicId());
        return invoke(null, param, ImMethodEnum.GET_GROUP_MUTED_ACCOUNT, tclass);
    }

    /**
     * 创建组
     *
     * @param imCreateGroupDTO
     * @return
     */
    public Object createGroup(ImCreateGroupDTO imCreateGroupDTO, Class tclass) {
        Map param = new HashMap();
        //群主 ID（需是 已导入 的帐号）。填写后自动添加到群成员中；如果不填，群没有群主；成员使用 AVChatroom（直播群）时，必须每次调用进群操作
        param.put("Owner_Account", imCreateGroupDTO.getOwnerAccount());
        // 群组形态，包括 Public（陌生人社交群），Private（即 Work，好友工作群），ChatRoom（即 Meeting，会议群），AVChatRoom（直播群），Community（社群）
        param.put("Type", imCreateGroupDTO.getType().getType());
        // 为了使得群组 ID 更加简单，便于记忆传播，腾讯云支持 App 在通过 REST API 创建群组时 自定义群组 ID
//        param.put("GroupId",);
        param.put("Name", imCreateGroupDTO.getName());
        // 群简介，最长240字节，使用 UTF-8 编码，1个汉字占3个字节
        param.put("Introduction", imCreateGroupDTO.getIntroduction());
        // 群公告，最长300字节，使用 UTF-8 编码，1个汉字占3个字节
        param.put("Notification", imCreateGroupDTO.getNotification());
        // 群头像 URL，最长100字节
        param.put("FaceUrl", imCreateGroupDTO.getFaceUrl());
        // 最大群成员数量，缺省时的默认值：付费套餐包上限，例如体验版是20，如果升级套餐包，需按照修改群基础资料修改这个字段
        param.put("MaxMemberCount", imCreateGroupDTO.getMaxMemberCount());
        // 申请加群处理方式。包含 FreeAccess（自由加入），NeedPermission（需要验证），DisableApply（禁止加群），不填默认为 NeedPermission（需要验证）
        //仅当创建支持申请加群的 群组 时，该字段有效。社群目前不支持此字段
        param.put("ApplyJoinOption", imCreateGroupDTO.getApplyJoinOption());
        // 群组维度的自定义字段，默认情况是没有的，可以通过 即时通信 IM 控制台 进行配置，详情请参阅 自定义字段
//        param.put("AppDefinedData","");
        // 初始群成员列表，最多100个；成员信息字段详情请参阅 群成员资料
//        param.put("MemberList","");
        // 群成员维度的自定义字段，默认情况是没有的，可以通过 即时通信 IM 控制台 进行配置，详情请参阅 自定义字段
//        param.put("AppMemberDefinedData","");
        // 是否支持话题选项，此字段只针对社群有效
//        param.put("SupportTopic","");
        return invoke(null, param, ImMethodEnum.CREATE_GROUP, tclass);
    }

    private Object invoke(Long userId, Map param, ImMethodEnum imMethodEnum, Class tclass) {
        TLSSigAPIv2 api = new TLSSigAPIv2(appId, key);
        String result = api.genUserSig("administrator", 15552000);
        Map map = new HashMap<>();
        map.put("sdkappid", "1400789568");
        map.put("identifier", "administrator");
        map.put("usersig", result);
        map.put("random", IdUtil.getSnowflake().nextId());
        map.put("contenttype", "json");
        StringJoiner info = new StringJoiner("&");
        map.forEach((o, o2) -> {
            info.add(o + "=" + o2);
        });
        log.info("请求目的:{}-----请求链接报文:{}----请求体报文:{}", imMethodEnum.getMethodDesc(), map, JSON.toJSON(param));
        // 傻逼腾讯的IM对接的时候必须把公共参数拼接到链接后面,在把请求参数放入到body里面.
        String post = HttpUtil.post(StrUtil.format("https://console.tim.qq.com/{}?{}", imMethodEnum.getMethodCode(), info), JSON.toJSONString(param));
        JSONObject record = JSONObject.parseObject(post);
        log.info("请求目的:{}-------响应报文:{}", imMethodEnum.getMethodDesc(), record);
        Object o = JSON.parseObject(record.toJSONString(), tclass);
        return o;
    }

    public static String getToken(Long userId) {
        TLSSigAPIv2 api = new TLSSigAPIv2(appId, key);
        String result = api.genUserSig(Convert.toStr(userId), 15552000);
        return result;
    }

}
